package com.wogu.jwa.web.admin;

import java.io.IOException;
import java.util.Map;
import java.util.HashMap;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.RequestDispatcher;

import com.wogu.jwa.web.admin.classes.Member;
import com.wogu.jwa.web.admin.model.GroupModel;

public class Group extends Member {

	public void addGet() throws IOException, ServletException, SQLException {
		String groupId = request.getParameter("groupid");
		if(null != groupId && 0 < Integer.valueOf(groupId)) {
			Map<String, String> group = GroupModel.getInstance().getGroup(null, "groupid=?", new String[]{groupId});
			request.setAttribute("group", group);
		}
		
		RequestDispatcher view = request.getRequestDispatcher("WEB-INF/template/group_add.jsp");
		view.forward(request, response);
	}
	
	public void addPost() throws IOException, ServletException, SQLException {
		String groupId = request.getParameter("groupid");
		final String groupName = request.getParameter("groupname");
		GroupModel groupModel = GroupModel.getInstance();
		int result  = 0;
		if(null != groupId && 0 < Integer.valueOf(groupId)) {
			result = groupModel.updateGroup(new HashMap<String, String>(){{
						put("groupname", groupName);
					}}, "groupid=?", new String[]{groupId});
		} else {
			result = groupModel.addGroup(new HashMap<String, String>(){{
				put("groupname", groupName);
			}});
		}
		
		if(result > 0) {
			response.sendRedirect(config.getProperty("site_root") + "/admin?c=group&a=manage");
		} else {
			response.sendRedirect(request.getHeader("referer"));
		}
	}
	
	public void manageGet() throws IOException, ServletException, SQLException {
		GroupModel groupModel = GroupModel.getInstance();
		Map<Integer, String> groups = groupModel.getGroups();
		request.setAttribute("groups", groups);
		RequestDispatcher view = request.getRequestDispatcher("/WEB-INF/template/group_manage.jsp");
		view.forward(request, response);
	}
}